package com.ssm.demo.util.aspect;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.demo.util.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author yk
 */
@Component
@Aspect
@Slf4j
public class PageAspect {

    @Around(value = "execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint point) throws Throwable {
        PageBean pageBean = null;
        for (Object e : point.getArgs()) {
            if (e instanceof PageBean) {
                pageBean = (PageBean) e;
                break;
            }
        }
        if (pageBean != null && pageBean.isPagination()) {
            PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
        }
        Object obj = point.proceed(point.getArgs());
        if (obj != null) {
            if (obj instanceof Page) {
                Page page = (Page) obj;
                PageInfo pageInfo = new PageInfo(page);
                pageBean.setTotal(Long.valueOf(pageInfo.getTotal()).intValue());
                return pageInfo.getList();
            }
        }
        return obj;
    }

}